package cn.billy.user.controller;

import cn.billy.basic.dto.RegisterDto;
import cn.billy.basic.exception.BusinessException;
import cn.billy.user.service.IUserService;
import cn.billy.user.domain.User;
import cn.billy.user.query.UserQuery;
import cn.billy.basic.utils.AjaxResult;
import cn.billy.basic.utils.PageList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    public IUserService userService;


    /**
     * 保存和修改公用的
     * @param user  传递的实体
     * @return Ajaxresult转换结果
     */
    @PutMapping
    public AjaxResult addOrUpdate(@RequestBody User user){
        try {
            if( user.getId()!=null)
                userService.update(user);
            else
                userService.save(user);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("保存对象失败！"+e.getMessage());
        }
    }
    /**
    * 删除对象信息
    * @param id
    * @return
    */
    @DeleteMapping(value="/{id}")
    public AjaxResult remove(@PathVariable("id") Long id){
        try {
            userService.remove(id);
            return AjaxResult.me();
        } catch (Exception e) {
        e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("删除对象失败！"+e.getMessage());
        }
    }
	
    //获取用户
    @GetMapping("/{id}")
    public User getById(@PathVariable("id")Long id)
    {
        return userService.getById(id);
    }


    /**
    * 查看所有的员工信息
    * @return
    */
    @GetMapping()
    public List<User> loadAll(){

        return userService.loadAll();
    }


    /**
    * 分页查询数据
    *
    * @param query 查询对象
    * @return PageList 分页对象
    */
    @PostMapping("/list")
    public PageList<User> queryData(@RequestBody UserQuery query)
    {
        return userService.queryData(query);
    }

    // /register/phone
    @PostMapping("/register/phone")
    public AjaxResult registerPhone(@RequestBody RegisterDto registerDto) {
        try {
            // 手机注册接口，传入前端的数据
            userService.phoneCodeRegister(registerDto);
            return AjaxResult.me();
        } catch (BusinessException e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage(e.getMessage());

        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("保存对象失败！");
        }
    }

    @PostMapping("/register/email")
    public AjaxResult registerEmail(@RequestBody RegisterDto registerDto){
        try {
            userService.registerEmail(registerDto);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("系统繁忙，请稍后重试！");
        }
    }
}
